package com.wjw.oauth2demo.config;

import com.wjw.oauth2demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.xml.ws.Endpoint;

/**
 * 授权服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier("redisTokenStore")
    private TokenStore tokenStore;

    //密码模式所需配置
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                .tokenStore(tokenStore);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //去授权服务器注册出来，这里简写成自定义进内存
        clients.inMemory()
                .withClient("admin")
                //配置client-id和client-serret 用于postman测试
                .secret(passwordEncoder.encode("kehuduanmima"))
                //访问token令牌有效期
                .accessTokenValiditySeconds(3600)
                //授权成功跳转
                .redirectUris("http://www.baidu.com")
                //申请的权限范围
                .scopes("all")
                //授权类型 授权码模式
                //.authorizedGrantTypes("authorization_code");
                .authorizedGrantTypes("password");

    }


}
